package com.huanhong.hik.util.callback;

import cn.hutool.core.util.StrUtil;
import com.huanhong.hik.bean.Result;
import com.huanhong.hik.socket.SocketIoClient;
import com.huanhong.hik.util.HCNetSDK;
import com.sun.jna.Pointer;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@NoArgsConstructor
@Slf4j
public class FRemoteCfgCallBackCardSet implements HCNetSDK.FRemoteConfigCallback {

    @Override
    public void invoke(int dwType, Pointer lpBuffer, int dwBufLen, Pointer pUserData) {
        log.info("长连接回调获取数据,NET_SDK_CALLBACK_TYPE_STATUS:{}", dwType);
        switch (dwType) {
            case 0:// NET_SDK_CALLBACK_TYPE_STATUS
                HCNetSDK.REMOTECONFIGSTATUS_CARD struCardStatus = new HCNetSDK.REMOTECONFIGSTATUS_CARD();
                struCardStatus.write();
                Pointer pInfoV30 = struCardStatus.getPointer();
                pInfoV30.write(0, lpBuffer.getByteArray(0, struCardStatus.size()), 0, struCardStatus.size());
                struCardStatus.read();

                int iStatus = 0;
                for (int i = 0; i < 4; i++) {
                    int ioffset = i * 8;
                    int iByte = struCardStatus.byStatus[i] & 0xff;
                    iStatus = iStatus + (iByte << ioffset);
                }

                switch (iStatus) {
                    case 1000:// NET_SDK_CALLBACK_STATUS_SUCCESS
                        log.info("下发卡参数成功,dwStatus:{}", iStatus);
                        if (null != SocketIoClient.socket) {
                            SocketIoClient.socket.emit("setCard", Result.success().toJsonString());
                        }
                        break;
                    case 1001:
                        log.info("正在下发卡参数中,dwStatus:" + iStatus);
                        break;
                    case 1002:
                        int iErrorCode = 0;
                        for (int i = 0; i < 4; i++) {
                            int ioffset = i * 8;
                            int iByte = struCardStatus.byErrorCode[i] & 0xff;
                            iErrorCode = iErrorCode + (iByte << ioffset);
                        }
                        log.error("下发卡参数失败, dwStatus:{},错误号:{}", iStatus, iErrorCode);
                        if (null != SocketIoClient.socket) {
                            SocketIoClient.socket.emit("setCard", Result.fail("4000", StrUtil.format("下发卡参数失败, dwStatus:{},错误号:{}", iStatus, iErrorCode)).toJsonString());
                        }
                        break;
                }
                break;
            default:
                break;
        }
    }
}
